HuggingFace 简介
什么是 Hugging Face?
Hugging Face 提供了一个强大的 AI 平台,支持 NLP、计算机视觉和多种 AI 任务。其 Transformers 库广泛应用于文本处理。
info
Hugging Face API 可用于 NLP 任务,如文本生成、情感分析、机器翻译等。
安装与环境准备
1. 安装 Hugging Face 库
pip install transformers torch
2. 获取 Hugging Face 访问令牌
- 访问 Hugging Face 官网
- 注册或登录账户
- 在 Settings 页面创建 API 令牌
caution
请勿公开 API 令牌,以免泄露。
基本 API 调用示例
- Python
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
result = classifier("Hugging Face 是一个很棒的 AI 平台!")
print(result)
Hugging Face 部署示例
- Flask API
- FastAPI API
from flask import Flask, request, jsonify
from transformers import pipeline
app = Flask(__name__)
classifier = pipeline("sentiment-analysis")
@app.route("/analyze", methods=["POST"])
def analyze():
data = request.json
result = classifier(data["text"])
return jsonify(result)
if __name__ == "__main__":
app.run(port=5000)
from fastapi import FastAPI
from transformers import pipeline
app = FastAPI()
classifier = pipeline("sentiment-analysis")
@app.post("/analyze")
def analyze(text: str):
return classifier(text)
进阶操作
使用 Hugging Face Hub 进行模型托管
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
def predict(text):
inputs = tokenizer(text, return_tensors="pt")
outputs = model(**inputs)
return torch.nn.functional.softmax(outputs.logits, dim=-1)
print(predict("Hugging Face is amazing!"))
结论
Hugging Face 提供了强大的 AI 计算能力,可用于文本、语音、图像等多种任务。无论是研究者还是开发人员,都可以利用 Hugging Face 进行高效的 AI 开发。